package org.snusmumr.android.media.tools;

import java.util.HashMap;

import org.snusmumr.android.media.util.Utils;

public class ArrayDataProvider implements ModelDataProvider {
	private static final String LABEL_SEPARATOR = ",";
	
	private static final String AUTHOR_NAME = "author_name";
	private static final String ITEM_NAME = "name";
	private static final String LABELS = "labels";
	private static final String CATEGORY = "category";
	private static final String COMMENT = "comment";
	
	private String[] data;
	private HashMap<String, Integer> headersMap;
	
	public ArrayDataProvider(String[] headers) {
		if(headers != null && headers.length > 0) {
			headersMap = new HashMap<String, Integer>(headers.length);
			for (int i = 0; i < headers.length; i++) {
				headersMap.put(headers[i], Integer.valueOf(i));
			}
		} else
			throw new IllegalStateException("headers array is null or empty");
	}
	
	public String getField(String column) throws ParseException {
		Integer index = headersMap.get(column);
		if(index == null)
			throw new ParseException("Cannot find value for column [" + column + "]");
		if(data.length <= index + 1)
			throw new ParseException("Cannot find value for column index " + index);
		return data[index.intValue()];
	}
	
	public void setData(String[] data) {
		this.data = data;
	}

	@Override
	public String getAuthor() throws ParseException {
		return getField(AUTHOR_NAME);
	}

	@Override
	public String getItemName() throws ParseException {
		return getField(ITEM_NAME);
	}

	@Override
	public String getItemComment() throws ParseException {
		return getField(COMMENT);
	}

	@Override
	public String[] getItemLabels() throws ParseException {
		String labelsStr = getField(LABELS);
		if(!Utils.isEmpty(labelsStr)) {
			return labelsStr.split(LABEL_SEPARATOR);
		}
		return null;
	}

	@Override
	public String getCategory() throws ParseException {
		return getField(CATEGORY);
	}

}
